/*// 引入UI组件
import Count from "../../components/Count";*/
/*优化写法:
* 将UI组件和容器组件结合成一个文件
* */
// 引入connect用于连接UI和redux
import {connect} from 'react-redux'

import {increment, decrement, incrementAsync} from "../../redux/actions/count";

import React, {Component} from 'react';

class Count extends Component {
  increment = () => {
    const {value} = this.selectedNum
    this.props.add(value * 1)
  }
  decrement = () => {
    const {value} = this.selectedNum
    this.props.minus(value * 1)
  }
  incrementIfOdd = () => {
    const {num, add} = this.props
    if (num % 2) {
      const {value} = this.selectedNum
      add(value * 1)
    }
  }
  incrementAsync = () => {
    const {value} = this.selectedNum
    this.props.addAsync(value * 1, 1000)
  }

  render() {
    const {num, people} = this.props
    return (
      <div>
        <h1>当前求和为: {num}, 下面那个容器组件的人数为：{people.length}</h1>
        <hr/>
        <select name="count" id="count" ref={c => this.selectedNum = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        <button onClick={this.increment}>increment</button>
        <button onClick={this.decrement}>decrement</button>
        <button onClick={this.incrementIfOdd}>incrementIfOdd</button>
        <button onClick={this.incrementAsync}>incrementAsync</button>
      </div>
    );
  }
}

// react-redux在调用该函数是，已经将store的state传入了. 该函数用于将state映射为props传入UI组件
const mapStateToProps = (state) => {
  return {num: state.sum, people: state.people}
}

// 该函数用于将dispatch行为以K,V形式(对象)映射为props传递给UI组件
/*const mapDispatchToProps = (dispatch) => {
  return {
    add: data => dispatch(createIncrementAction(data)),
    minus: data => dispatch(createDecrementAction(data)),
    addAsync: (data, wait) => dispatch(creatIncrementActionAsync(data, wait))
  }
}*/

/*
mapDispathToProps可以简写为一个对象，V为创建action的函数，react-redux会接收到action对象并自动dispatch
 */
const mapDispatchToProps = {
  add: increment,
  minus: decrement,
  addAsync: incrementAsync

}

// 导出容器组件
export default connect(mapStateToProps, mapDispatchToProps)(Count);
